package cn.jetpiece.cloud.core.filters;

import cn.hutool.core.util.StrUtil;
import cn.jetpiece.cloud.core.consts.GatewayConstants;
import cn.jetpiece.cloud.core.exception.GatewayException;
import cn.jetpiece.cloud.core.exception.enums.GatewayExceptionEnum;
import cn.jetpiece.cloud.core.util.AuthenticationUtils;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

/**
 * jwt的网关校验过滤器（针对于部分路由，非全局过滤器）
 * <p>
 * ps: GatewayFilterFactory结尾的过滤器可以在application.yml中配置
 *
 * @author XuJZ
 */
@Component
public class JwtTokenGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {

    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            //当前请求的路径
            ServerHttpRequest request = exchange.getRequest();
            String ignoreUrl = request.getHeaders().getFirst(GatewayConstants.IGNORE_URL);
            if (StrUtil.isNotBlank(ignoreUrl)) {
                return chain.filter(exchange.mutate().request(request).build());
            }
            GatewayExceptionEnum anEnum = AuthenticationUtils.checkToken(request);
            if (anEnum != null) {
                throw new GatewayException(anEnum);
            }
            return chain.filter(exchange.mutate().request(request).build());
        };
    }

}
